home *** CD-ROM | disk | FTP | other *** search
- From: Mats.Henricson@eua.ericsson.se (Mats Henricson)
- Message-ID: <9601161450.AA22214@euax3i4c06.eua.ericsson.se>
- X-Original-Date: Tue, 16 Jan 1996 15:50:54 +0100
- Path: in2.uu.net!bounce-back
- Date: 16 Jan 96 15:27:17 GMT
- Approved: fjh@cs.mu.oz.au
- Organization: -
- Newsgroups: comp.std.c++
- Return-Path: <daemon@migs.UCAR.EDU>
- Subject: Re: can initialization be used with new[]?
- X-Auth: PGPMoose V1.1 PGP comp.std.c++
- iQBFAgUBMPvD9eEDnX0m9pzZAQGsFwF/fRobrVXbB/37CffU7JbZPuZt6yAE02eu
- mEp+rJii8/TNkKGuc3R12CJhfbmuH4jO
- =C85d
-
- In article <l8291j9wix9.fsf@neppari.cs.hut.fi>,
- "Lassi A. Tuura" <Lassi.Tuura@hut.fi> writes:
- >One compiler I need to use has problems with the following code:
- >---------------
- >#include <new.h>
- >class T {
- >public:
- > T (int n) : _n (n) { }
- > T (const T &ref) : _n (ref._n) { }
- > ~T () { }
- >
- >private:
- > int _n;
- >};
- >
- >void f ()
- >{
- > T *ptr = new T [10] (1); // line 14
- >}
- >---------------
- >
- >In particular, it complains about the initializer to the vector new:
- > CC: "test.cc", line 14: error: initializer for array of class object
- > created using `new' (1248)
- >
- >Another compiler has no problems with the code, and the one giving the
- >error message has not proved to be reliable. The question is: Is this
- >legal C++? I read thru 5.3.4 from the april draft and as far as I
- >understood the code was flagged ill-formed. Did I interpret the draft
- >correctly? If I did, how am I supposed to allocate an array of
- >objects of class T? With explicit calls to operator new and placement
- >new?
-
- The code is not legal. The reason is that the default constructor,
- which is usually T::T(), will be used when you allocate arrays of T:s.
- The compiler will generate a T::T() for you only in one case, namely
- when you yourself have explicitly delared no other constructors. In
- this case you have such a constructor, T::T(int n). Therefore the
- compiler will not make a T::T() for you, which makes it impossible to
- allocate arrays of T:s.
-
- The fix is simple: Get yourself a T::T(). Another option is to give
- the the int parameter a default value, usually 0 works OK. This would
- give you this class:
-
- class T
- {
- public:
- T (int n = 0) : _n (n) { }
- T (const T &ref) : _n (ref._n) { }
- ~T () { }
-
- private:
- int _n;
- };
-
- A side note: Don't use "_" as a prefix to identifiers, since that is
- almost illegal according to the language. It is much better to use "_"
- as a suffix.
-
- Mats Henricson
- Stockholm
- Sweden
- ---
- [ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
- Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
- is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
-